<template>
  <div class="house-details-container">
    <el-card>
      <div class="management-title">
        <h2>房源详情 - {{ buildingName }} ({{ plotName }})</h2>
        <el-button @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
      </div>

      <!-- 楼栋信息展示 -->
      <div class="building-info-section" v-if="buildingInfo.name">
        <div class="building-info-card">
          <div class="building-info-left">
            <div v-if="buildingInfo.imageUrl" class="building-image">
              <img :src="buildingInfo.imageUrl" :alt="`${buildingInfo.name}栋`" @error="handleImageError" />
            </div>
            <div v-else class="no-image">
              <el-icon size="48"><Picture /></el-icon>
              <p>暂无图片</p>
            </div>
          </div>
          
          <div class="building-info-right">
            <h3 class="building-info-title">{{ buildingInfo.name }}栋</h3>
            <div class="building-info-details">
              <div class="info-item">
                <el-icon><House /></el-icon>
                <span>单元数：{{ buildingInfo.unitNum }}个</span>
              </div>
              <div class="info-item">
                <el-icon><OfficeBuilding /></el-icon>
                <span>楼层数：{{ buildingInfo.floorNum }}层</span>
              </div>
              <div class="info-item">
                <el-icon><Grid /></el-icon>
                <span>房屋数：{{ buildingInfo.houseNum }}套</span>
              </div>
              <div class="info-item" v-if="buildingInfo.createDate">
                <el-icon><Calendar /></el-icon>
                <span>创建时间：{{ formatDate(buildingInfo.createDate) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="house-header">
        <div class="header-left">
          <el-button type="primary" @click="handleAddHouse">
            <el-icon><Plus /></el-icon>
            新增房源
          </el-button>
          <el-button type="success" @click="handleBatchGenerate">
            <el-icon><Magic /></el-icon>
            批量生成房源
          </el-button>
        </div>
        <div class="header-right">
          <span class="house-count">共 {{ houseList.length }} 套房源</span>
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="单元">
            <el-select v-model="filterForm.unitNum" placeholder="选择单元" clearable style="width: 120px">
              <el-option
                v-for="unit in unitOptions"
                :key="unit"
                :label="`${unit}单元`"
                :value="unit"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="楼层">
            <el-select v-model="filterForm.floorNum" placeholder="选择楼层" clearable style="width: 120px">
              <el-option
                v-for="floor in floorOptions"
                :key="floor"
                :label="`${floor}层`"
                :value="floor"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="选择状态" clearable style="width: 120px">
              <el-option label="空闲" value="0" />
              <el-option label="已租" value="1" />
              <el-option label="维修" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="handleResetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 房源网格 -->
      <div class="house-grid" v-loading="loading">
        <div 
          v-for="house in filteredHouseList" 
          :key="house.id"
          class="house-card"
          :class="getHouseCardClass(house)"
          @click="handleHouseClick(house)"
        >
          <div class="house-header">
            <div class="house-number">
              <h3>{{ house.houseNum }}号</h3>
              <el-tag :type="getStatusTagType(house.status)" size="small">
                {{ getStatusText(house.status) }}
              </el-tag>
            </div>
          </div>
          
          <div class="house-info">
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">单元：</span>
                <span class="info-value">{{ house.unitNum }}单元</span>
              </div>
              <div class="info-item">
                <span class="info-label">楼层：</span>
                <span class="info-value">{{ house.floorNum }}层</span>
              </div>
              <div class="info-item">
                <span class="info-label">户型：</span>
                <span class="info-value">{{ house.typeName || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">面积：</span>
                <span class="info-value">{{ house.houseArea || 0 }}㎡</span>
              </div>
              <div class="info-item" v-if="house.rentPrice">
                <span class="info-label">租金：</span>
                <span class="info-value price">{{ formatMoney(house.rentPrice) }}元/月</span>
              </div>
              <div class="info-item" v-if="house.tenantName">
                <span class="info-label">租户：</span>
                <span class="info-value">{{ house.tenantName }}</span>
              </div>
            </div>
          </div>
          
          <div class="house-actions">
            <el-button size="small" type="primary" @click.stop="handleEditHouse(house)">
              编辑
            </el-button>
            <el-button size="small" type="success" @click.stop="handleViewContract(house)" v-if="house.status === 1">
              查看合同
            </el-button>
            <el-button size="small" type="danger" @click.stop="handleDeleteHouse(house)">
              删除
            </el-button>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && filteredHouseList.length === 0" class="empty-house">
          <el-empty description="暂无房源数据">
            <el-button type="primary" @click="handleAddHouse">添加房源</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="table-pagination" v-if="total > 0">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑房源对话框 -->
    <el-dialog
      :title="isEdit ? '编辑房源' : '新增房源'"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房号" prop="houseNum">
              <el-input v-model="formData.houseNum" placeholder="请输入房号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单元" prop="unitNum">
              <el-input-number v-model="formData.unitNum" :min="1" :max="20" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorNum">
              <el-input-number v-model="formData.floorNum" :min="1" :max="100" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="户型" prop="typeId">
              <el-select v-model="formData.typeId" placeholder="请选择户型" style="width: 100%">
                <el-option
                  v-for="type in typeList"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="建筑面积" prop="houseArea">
              <el-input v-model="formData.houseArea" placeholder="请输入建筑面积">
                <template #suffix>㎡</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租金" prop="rentPrice">
              <el-input v-model="formData.rentPrice" placeholder="请输入租金">
                <template #suffix>元/月</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="房源状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">空闲</el-radio>
            <el-radio :label="1">已租</el-radio>
            <el-radio :label="2">维修</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { Plus, Magic, House, OfficeBuilding, Grid, Calendar, Picture } from '@element-plus/icons-vue';
import baseService from "@/service/baseService";

// 响应式数据
const loading = ref(false);
const houseList = ref<any[]>([]);
const buildingInfo = ref<any>({});
const typeList = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = 20;

// 对话框相关
const dialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const formRef = ref<InstanceType<typeof ElForm>>();

// 筛选表单
const filterForm = reactive({
  unitNum: null,
  floorNum: null,
  status: null
});

// 表单数据
const formData = reactive({
  id: null,
  houseNum: '',
  buildingId: null,
  unitNum: 1,
  floorNum: 1,
  typeId: null,
  houseArea: '',
  rentPrice: '',
  status: 0,
  remark: ''
});

// 表单验证规则
const formRules = {
  houseNum: [
    { required: true, message: '请输入房号', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  unitNum: [
    { required: true, message: '请输入单元号', trigger: 'blur' }
  ],
  floorNum: [
    { required: true, message: '请输入楼层号', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '请选择户型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择房源状态', trigger: 'change' }
  ]
};

// 获取URL参数（兼容hash模式）
const getUrlParams = () => {
  const hash = window.location.hash;
  const queryString = hash.includes('?') ? hash.split('?')[1] : window.location.search.substring(1);
  return new URLSearchParams(queryString);
};

const urlParams = getUrlParams();
const buildingId = ref(urlParams.get('buildingId') || '');
const buildingName = ref(decodeURIComponent(urlParams.get('buildingName') || ''));
const plotName = ref(decodeURIComponent(urlParams.get('plotName') || ''));

// 计算属性
const unitOptions = computed(() => {
  if (!buildingInfo.value.unitNum) return [];
  return Array.from({ length: buildingInfo.value.unitNum }, (_, i) => i + 1);
});

const floorOptions = computed(() => {
  if (!buildingInfo.value.floorNum) return [];
  return Array.from({ length: buildingInfo.value.floorNum }, (_, i) => i + 1);
});

const filteredHouseList = computed(() => {
  let filtered = [...houseList.value];
  
  if (filterForm.unitNum !== null) {
    filtered = filtered.filter(house => house.unitNum === filterForm.unitNum);
  }
  
  if (filterForm.floorNum !== null) {
    filtered = filtered.filter(house => house.floorNum === filterForm.floorNum);
  }
  
  if (filterForm.status !== null) {
    filtered = filtered.filter(house => house.status === parseInt(filterForm.status));
  }
  
  return filtered;
});

// 工具函数
const formatDate = (dateStr: string) => {
  if (!dateStr) return '暂无';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

const formatMoney = (amount: number) => {
  if (!amount) return '0';
  return amount.toLocaleString('zh-CN');
};

const getStatusText = (status: number) => {
  const statusMap = {
    0: '空闲',
    1: '已租',
    2: '维修'
  };
  return statusMap[status] || '未知';
};

const getStatusTagType = (status: number) => {
  const typeMap = {
    0: 'success',
    1: 'warning',
    2: 'danger'
  };
  return typeMap[status] || 'info';
};

const getHouseCardClass = (house: any) => {
  const classes = ['house-card'];
  if (house.status === 0) classes.push('available');
  if (house.status === 1) classes.push('rented');
  if (house.status === 2) classes.push('maintenance');
  return classes.join(' ');
};

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.src = '';
};
